package com.srwl.mytx.activity;

import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.srwl.mytx.R;
import com.srwl.mytx.tao.av.FileUtils;
import com.srwl.mytx.utils.GlideLoadUtils;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class MyVideoPlayActivity extends BaseActivity implements View.OnClickListener {
    private SurfaceView sv_video;
    private SurfaceHolder mSurfaceHolder;
    private MediaPlayer mMediaPlayer;
    private String mTempVideoPath;
    private ImageView iv_back;
    private Animation anim_playbutton;
    private ImageView iv_playbutton;
    private Handler mSafeHandler;
    private boolean isErrorVideo = false;
    public boolean mUploading = false;
    private boolean isSaving = false;
    //    private TBAVRecorderManager mRecorderManager;
//    private NewDialog mNewDialog;
    private ImageView mImgCover;
    private Bitmap mCoverBitmap;
    private boolean mPubSuccess;
    private JSONObject mResultObj;
    private int mVideoDuration;
    private String mTempFramePicPath;
    private int mVideoSize;
    private int mFramePicWidth;
    private int mFramePicHeight;
    private TextView size_video;
    private String mUploadID;
    private String mUploadTarget;
    private final SurfaceHolder.Callback surfaceCallback;

    private Button btn_commit;

    public MyVideoPlayActivity() {
        surfaceCallback = new SurfaceHolder.Callback() {
            public void surfaceCreated(SurfaceHolder holder) {
                mSurfaceHolder = holder;
                initVideo();
                startVideo();
            }

            public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
            }

            public void surfaceDestroyed(SurfaceHolder holder) {
                mSurfaceHolder = null;
                stopVideo();
            }
        };
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_play_video);
        sv_video = findViewById(R.id.sv_video);
        sv_video.setOnClickListener(this);
        mSurfaceHolder = sv_video.getHolder();
        mSurfaceHolder.addCallback(surfaceCallback);
        mSurfaceHolder.setType(3);
        mSafeHandler = new Handler();
        iv_back = findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);
        iv_playbutton = findViewById(R.id.iv_playbutton);
        iv_playbutton.setVisibility(View.GONE);
        size_video = findViewById(R.id.size_video);
        mImgCover = findViewById(R.id.img_cover);

        try {
            Bundle bundle = getIntent().getExtras();
            mTempVideoPath = bundle.getString("videoPath");
            mTempFramePicPath = bundle.getString("framePicPath");
            mVideoDuration = bundle.getInt("videoDuration");
            mVideoSize = bundle.getInt("videoSize");
            mFramePicWidth = bundle.getInt("framePicWidth");
            mFramePicHeight = bundle.getInt("framePicHeight");
            mUploadID = bundle.getString("uploadID");
            mUploadTarget = bundle.getString("uploadTarget");
        } catch (Exception var3) {
            ;
        }

        if (TextUtils.isEmpty(mTempVideoPath)) {
            finish();
        } else {
            if (mVideoSize != 0) {
                String size;

                if (mVideoSize > 1024 * 1024) {
                    int sizeM = mVideoSize / (1024 * 1024);
                    String remainder = String.valueOf(mVideoSize % (1024 * 1024)).substring(0, 2);//取两位数
                    size = sizeM + "." + remainder + "M";
                } else if (mVideoSize > 1024) {
                    int sizeK = mVideoSize / 1024;
                    size = sizeK + "KB";
                } else {
                    size = mVideoSize + "B";
                }
                size_video.setText(size);
            } else {
                size_video.setVisibility(View.INVISIBLE);
            }


//            mCoverBitmap = ThumbnailUtils.createVideoThumbnail(mTempVideoPath, 1);
//            mImgCover.setImageBitmap(mCoverBitmap);
            //Glide.with(this).load(mTempVideoPath).into(mImgCover);
            GlideLoadUtils.glideLoad(this, mTempVideoPath, mImgCover);
            // tv_previewok = (TextView)findViewById(R.id.tv_previewok);
            // tv_previewok.setOnClickListener(this);
            // changeStyle();
            btn_commit = findViewById(R.id.btn_commit);
            btn_commit.setOnClickListener(this);
        }
    }


    private void initVideo() {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setAudioStreamType(3);
        mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            public boolean onError(MediaPlayer mp, int what, int extra) {
                finishVideo();
                stopVideo();
                isErrorVideo = true;
                showToast(getString(R.string.taorecorder_videoerror));
                return false;
            }
        });
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            public void onCompletion(MediaPlayer mp) {
                mMediaPlayer.seekTo(0);
                mMediaPlayer.start();
            }
        });
        mMediaPlayer.setDisplay(mSurfaceHolder);

        try {
            mMediaPlayer.setDataSource(mTempVideoPath);
            mMediaPlayer.prepare();
        } catch (IllegalArgumentException var2) {
            var2.printStackTrace();
        } catch (SecurityException var3) {
            var3.printStackTrace();
        } catch (IllegalStateException var4) {
            var4.printStackTrace();
        } catch (IOException var5) {
            var5.printStackTrace();
        }

        if (anim_playbutton == null) {
            anim_playbutton = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.taorecorder_alpha_hide);
            anim_playbutton.setAnimationListener(new Animation.AnimationListener() {
                public void onAnimationStart(Animation animation) {
                }

                public void onAnimationEnd(Animation animation) {
                    if (!isErrorVideo) {
                        iv_playbutton.setVisibility(View.GONE);
                    }

                }

                public void onAnimationRepeat(Animation animation) {
                }
            });
        }

    }

    public void startVideo() {
        mMediaPlayer.start();
        iv_playbutton.setVisibility(View.GONE);
        mImgCover.setVisibility(View.GONE);
        iv_playbutton.startAnimation(anim_playbutton);
    }

    public void pauseVideo() {
        if (mMediaPlayer != null && iv_playbutton != null) {
            mMediaPlayer.pause();
            iv_playbutton.setVisibility(View.VISIBLE);
        }
    }

    public void finishVideo() {
        mImgCover.setVisibility(View.VISIBLE);
        iv_playbutton.setVisibility(View.VISIBLE);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    public void stopVideo() {
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }

        if (iv_playbutton != null) {
            iv_playbutton.setVisibility(View.VISIBLE);
        }

    }

    public void onResume() {
        super.onResume();
//        IMCommitManager.pageAppear(this);
    }

    public void onPause() {
        super.onPause();
//        IMCommitManager.pageDisappear(this);
    }

    protected void onDestroy() {
        stopVideo();
//        if (mRecorderManager != null) {
//            mRecorderManager.destroy();
//        }

        if (mCoverBitmap != null && !mCoverBitmap.isRecycled()) {
            mCoverBitmap.recycle();
        }

        super.onDestroy();
    }

    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.iv_back:
                finish();
                break;
//            case R.id.tv_previewok:
//                IMCommitManager.commitClick(IMCommitManager.getActivityPageName(this), "Video_Send");
//                if (isErrorVideo) {
//                    showToast(getString(R.string.taorecorder_videoerror));
//                    return;
//                }
//
//                if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
//                    pauseVideo();
//                }
//
//                publish();
//                break;
            case R.id.sv_video:
                if (isErrorVideo || mMediaPlayer == null) {
                    showToast(getString(R.string.taorecorder_videoerror));
                    return;
                }

                if (mMediaPlayer.isPlaying()) {
                    pauseVideo();
                } else {
                    startVideo();
                }
                break;
            case R.id.btn_commit:
                if (isErrorVideo) {
                    showToast(getString(R.string.taorecorder_videoerror));
                    return;
                }

                if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                    pauseVideo();
                }

                publish();

        }

    }

    public void finish() {
        if (mPubSuccess) {
            setResult(-1, getIntent());
        } else {
            setResult(0, getIntent());
        }

        super.finish();
    }

    private void publish() {
        stopVideo();
        mPubSuccess = true;
        // 把视频文件复制一份，并替换掉intent 中的视频文件地址
        String dir = this.getExternalCacheDir().getAbsolutePath();
        String videoName = UUID.randomUUID().toString().replaceAll("-", "");
        final String targetVideoPath = dir + File.separator + videoName + "_output.mp4";
        FileUtils.copyFile(mTempVideoPath, targetVideoPath);
        getIntent().putExtra("videoPath", targetVideoPath);
        finish();
    }

}
